package com.macro.mall.controller.callbak;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;

// XhsSignatureService.java
@Service
@Slf4j
public class XhsSignatureService {

    public boolean verifySignature(
            String signature,
            String token,
            String timestamp,
            String nonce,
            String encryptedBody) {

        try {
            log.debug("签名验证参数 - signature: {}, token: {}, timestamp: {}, nonce: {}, encryptedBody: {}",
                    signature, token, timestamp, nonce, encryptedBody);
            String calculated = generateSignature(token, timestamp, nonce, encryptedBody);
            log.debug("计算得到的签名: {}, 期望签名: {}", calculated, signature);
            boolean equals = calculated.equals(signature);
            log.debug("签名验证结果: {}", equals);
            return equals;
        } catch (Exception e) {
            log.error("生成签名失败", e);
            return false;
        }
    }

    public String generateSignature(
            String token,
            String timestamp,
            String nonce,
            String encryptedBody) throws Exception {


        String[] array = new String[]{token, timestamp, nonce, encryptedBody};
        Arrays.sort(array);
        String joined = String.join("", array);

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(joined.getBytes(StandardCharsets.UTF_8));
        byte[] digest = md.digest();

        StringBuilder hexStr = new StringBuilder();
        for (byte b : digest) {
            String shaHex = Integer.toHexString(b & 0xFF);
            if (shaHex.length() < 2) {
                hexStr.append(0);
            }
            hexStr.append(shaHex);
        }

        return hexStr.toString();
    }
}
